import sys

import click
from flask.cli import with_appcontext

# try:
#     app = sys.modules["app"].adp_app
# except KeyError:
#     try:
#         from flask import current_app as app
#         if isinstance(app, Flask):
#             raise ImportError
#     except ImportError:
#         app = sys.modules["app"].App(__name__)


@click.command("ishell", context_settings={"ignore_unknown_options": True})
@click.argument("ipython_args", nargs=-1, type=click.UNPROCESSED)
@with_appcontext
def ishell(ipython_args):
    """flask shell 的 ipython 支持版本"""
    import IPython
    from flask import current_app
    from IPython.terminal.ipapp import load_default_config
    from traitlets.config.loader import Config

    from configs.settings import BASE_DIR
    from tools import cache, db, redis_conn
    from utils import crypto
    from utils.utils import init_openstack

    if "IPYTHON_CONFIG" in current_app.config:
        config = Config(current_app.config["IPYTHON_CONFIG"])
    else:
        config = load_default_config()

    config.TerminalInteractiveShell.banner1 = (
        f"Python {sys.version} on {sys.platform} \n"
        f"Python Path: {sys.base_prefix} \n"
        f"IPython: {IPython.__version__} \n"
        f"App: {current_app.import_name} [{current_app.env}] \n\n"
        f"Current Project: {BASE_DIR.name} \n"
    )

    namespace = current_app.make_shell_context()
    namespace.update(
        {
            "db": db,
            "cache": cache,
            "redis_conn": redis_conn,
            "crypto": crypto,
            "init_openstack": init_openstack,
        }
    )

    IPython.start_ipython(
        argv=ipython_args,
        user_ns=namespace,
        config=config,
    )
